package com.kingland.neusoft.course.controller;
import com.kingland.neusoft.course.mapper.dao.BookModel;
import com.kingland.neusoft.course.service.BookService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
public class BookController {
    private final BookModel bookModel;
    private final BookService bookService;

    public BookController(BookModel bookModel, BookService bookService) {
        this.bookModel = bookModel;
        this.bookService = bookService;
    }

    @PostMapping("/books")
    public void addBook(@RequestBody  BookModel bookModel){
        System.out.println(bookModel);
        bookService.addBook(bookModel);
    }

    @GetMapping("/books/count")
    public Map<String, Integer> countUser() {
        Integer userCount = bookService.count();
        return Map.of("count", userCount);
    }

    @GetMapping("/books")
    public List<BookModel> getAllBook() {
        return bookService.selectAllBook();
    }

    @GetMapping("/books/{bookName}")
    public BookModel getBookById(@PathVariable("bookName") String bookName) {
        return bookService.selectBook(bookName);
    }

    @DeleteMapping("/books/{bookId}")
    @PreAuthorize("hasAnyAuthority('role_admin')")
    public ResponseEntity deleteBook(@PathVariable("bookId") Long bookId) {
        if (bookService.deleteBook(bookId) == 1) {
            // 204
            return ResponseEntity.noContent().build();
        } else {
            // 404
            return ResponseEntity.notFound().build();
        }
    }



}
